<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\MallOrder;
use App\Models\MallOrderComment;
use App\Models\MallOrderProduct;
use App\Models\Product;
use Illuminate\Http\Request;

class OrderCommentController extends BaseController
{

    public $model = MallOrderComment::class;

    public function index(Request $request) {
        $this->validate($request, [
            'product_id' => 'required'
        ]);
        $product_id = $request->input('product_id');
        $list = MallOrderComment::withCertain('user', ['nickname', 'avatar_url'])
            ->where('product_id', $product_id)
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));

        $info = null;
        return $this->paginate($list, $info);
    }


    /**
     * 删除
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function destroy(Request $request)
    {
        $this->validate($request, [
            'comment_id' => 'required',
        ]);
        $id = \request('comment_id');
        $comment = OrderComment::find($id);
        if (!$comment)
            return $this->failed("评论不存在");

        return \DB::transaction(function () use ($comment) {
            $entity_model = new Service();
            $entity_model->where('id', $comment->entity_id)->increment('comment_num', -$comment->reply_count);
            return $this->success($comment->id);
        });
    }

    /**
     * 评论
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function store(Request $request) {
        $this->validate($request, [
            'list' => 'required',
        ]);
        $user = $this->getUser();
        $input = $request->input();

        try {
            \DB::transaction(function () use($input, $user){
                $list = json_decode($input['list'], true);

                $order_id = 0;
                foreach ($list as $item) {
                    $order_product = MallOrderProduct::find($item['order_product_id']);
                    if (!$order_product)
                        $this->failed('子订单号不存在');

                    $order_id = $order_product->order_id;
                    $product = Product::find($order_product->product_id);
                    if (!$product)
                        continue;

                    MallOrderComment::create([
                        'user_id' => $user->id,
                        'order_id' => $order_id,
                        'product_id' =>$product->id,
                        'order_product_id' => $item['order_product_id'],
                        'message' => $item['message'],
                        'star' => $item['star'],
                        'file' => $item['file'] ?? null,
                        'is_anonymous' => $item['is_anonymous'] ?? 0
                    ]);

                    $res = MallOrderComment::selectRaw('sum(star) as total_star , count(*) as total')
                        ->where('product_id', $item['order_product_id'])->first();
                    $total_star = $res['total_star'] ?? 0;
                    $total = $res['total'] ?? 0;
                    $temp = ( $total_star / 100) + $item['star'] / ($total + 1);
                    $score = number_format($temp, 2) * 100;

                    $product->score = $score;
                    $product->comment_num = $product->comment_num + 1;
                    $product->save();

                }

                $order_id && MallOrder::where('id', $order_id)->update(['comment_status' => 2]);
            });
            return $this->success([]);
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->failed($e->getMessage());
        }

    }

    public function info(Request $request)
    {
        $this->validate($request, [
           'order_id' => 'required'
        ]);
        $input = $request->input();
        $comment = MallOrderComment::where('order_id', $input['order_id'])->withCertain('user', ['nickname', 'avatar_url'])
            ->paginate(\request('per_page', 20));
        return $this->paginate($comment);
    }

}

